package com.app.studyroom.dialog;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

import android.widget.EditText;
import android.widget.TextView;

import com.app.studyroom.AdminDashboardActivity;
import com.app.studyroom.LoginActivity;
import com.app.studyroom.PersonalCenterActivity;
import com.app.studyroom.R;
import com.app.studyroom.api.ApiClient;
import com.app.studyroom.api.ApiResponse;
import com.app.studyroom.api.ApiService;
import com.app.studyroom.api.model.ssrUser.IsUserBindResponse;
import com.app.studyroom.api.model.ssrUser.LoginRequest;
import com.app.studyroom.db.UserInfo;
import com.app.studyroom.peripherals.icCardRead.CardReaderGuard;
import com.google.gson.Gson;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ICCardLoginDialog extends CustomSizeDialog {

    private final Context context;
    private EditText etCardInput;
    private TextView tvCardId, tvCardStatus;

    public ICCardLoginDialog(Context ctx) {
        super(ctx, R.layout.dialog_ic_card_login, 0.7f, 0.55f);
        this.context = ctx;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupView();
    }
    private void setupView() {
        tvCardId = findViewById(R.id.tvCardId);
        tvCardStatus = findViewById(R.id.tvCardStatus);
        etCardInput = findViewById(R.id.etCardInput);

        etCardInput.setInputType(android.text.InputType.TYPE_NULL);
        etCardInput.setShowSoftInputOnFocus(false);
        etCardInput.requestFocus();

        etCardInput.setOnKeyListener((v, k, e) -> {
            if (e.getAction() == KeyEvent.ACTION_DOWN &&
                    (k == KeyEvent.KEYCODE_ENTER || k == KeyEvent.KEYCODE_NUMPAD_ENTER)) {
                String cid = etCardInput.getText().toString().trim();
                if (cid.isEmpty()) return true;
                tvCardId.setText(cid);
                tvCardStatus.setText("验证中…");
                checkLoginAsync(cid);
                return true;
            }
            return false;
        });

        findViewById(R.id.btnCancel).setOnClickListener(v -> {
            CardReaderGuard.isReadingCard = false;
            dismiss();
        });

        CardReaderGuard.isReadingCard = true;
    }

    private void checkLoginAsync(String cardId) {
        ApiService api = ApiClient.getClient().create(ApiService.class);
        LoginRequest body = new LoginRequest(cardId);

        Log.d("IC-LOGIN", "请求体：" + new Gson().toJson(body));

        api.login(body).enqueue(new Callback<ApiResponse<UserInfo>>() {
            @Override
            public void onResponse(Call<ApiResponse<UserInfo>> call, Response<ApiResponse<UserInfo>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                    UserInfo user = response.body().getData();
                    String userBs = user.getUserBs();
                    boolean isLoginAllowed = "用户".equals(userBs) ||
                            "区域管理员".equals(userBs) ||
                            "超级管理员".equals(userBs);

                    if (isLoginAllowed) {
                        saveLoginInfo(user, response.body().getToken());
                    } else {
                        tvCardStatus.setText("权限不符合，无法登录");
                        resetInput();
                    }
                } else {
                    tvCardStatus.setText("登录失败：" + (response.body() != null ? response.body().getMessage() : "未知错误"));
                    resetInput();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<UserInfo>> call, Throwable t) {
                tvCardStatus.setText("网络错误：" + t.getMessage());
                resetInput();
            }
        });
    }

    private void saveLoginInfo(UserInfo user, String token) {
        SharedPreferences sp = context.getSharedPreferences("Session", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        editor.putString("token", token);
        editor.putLong("userId", user.getId());
        editor.putString("userName", user.getUserName());
        editor.putString("userZjh", user.getUserZjh());
        editor.putString("userSjh", user.getUserSjh());
        editor.putString("userNumber", user.getUserNumber());
        editor.putString("userBs", user.getUserBs());
        editor.putString("qy", user.getQy());
        editor.putString("identity", user.getUserBs());
        editor.putString("userImage", user.getUserImage());
        editor.putString("studyTime", user.getStudyTime());
        editor.apply();

        ApiClient.getClient().create(ApiService.class).isUserBind(token)
                .enqueue(new Callback<ApiResponse<IsUserBindResponse>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<IsUserBindResponse>> call, Response<ApiResponse<IsUserBindResponse>> response) {
                        if (response.isSuccessful() && response.body() != null && response.body().isSuccess()) {
                            IsUserBindResponse bindInfo = response.body().getData();
                            SharedPreferences.Editor bindEditor = sp.edit();
                            bindEditor.putBoolean("isBind", bindInfo.isBind());
                            bindEditor.putString("bindSeatPlace", bindInfo.getSeatPlace());
                            bindEditor.putString("bindSeatNum", bindInfo.getSeatNum());
                            bindEditor.apply();
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<IsUserBindResponse>> call, Throwable t) {
                        Log.e("BindCheck", "获取绑定信息失败：" + t.getMessage());
                    }
                });

        tvCardStatus.setText("登录成功");
        CardReaderGuard.isReadingCard = false;
        dismiss();

        String role = user.getUserBs();
        Intent target = new Intent(context,
                ("区域管理员".equals(role) || "超级管理员".equals(role)) ?
                        AdminDashboardActivity.class : PersonalCenterActivity.class);
        target.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(target);
        if (context instanceof LoginActivity) ((LoginActivity) context).finish();
    }

    private void resetInput() {
        tvCardId.setText("");
        etCardInput.setText("");
        etCardInput.requestFocus();
    }

    @Override
    public void dismiss() {
        CardReaderGuard.isReadingCard = false;
        super.dismiss();
    }
}
